import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'view-design'
import { localRemove, getToken, removeToken, setTitle } from '@/libs/util'
import config from '@/config'
const { homeName } = config

Vue.use(Router)

const createRouter = () => new Router({
  mode: 'hash', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: routes
})

const router = createRouter()

// 重置路由，解决路由重复问题： Duplicate named routes definition: { name: "doc", path: "doc" }
export function resetRouter () {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

// 解决报错：Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/home
// 参考至：https://blog.csdn.net/qq_36437172/article/details/108269846
const VueRouterPush = Router.prototype.push
Router.prototype.push = function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

// const router = new Router({
//   routes,
//   mode: 'history'
// })

const LOGIN_PAGE_NAME = 'login'

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    if (store.state.user.hasGetInfo) {
      next()
    } else {
      store.dispatch('getUserInfo').then(user => {
        // 解决刷新出现的白屏bug，next({ ...to })的目的,是保证路由添加完了再进入页面
        next({ ...to, replace: true })
      }).catch(() => {
        removeToken() // 清除token
        localRemove('tagNaveList')
        next({
          name: 'login'
        })
      })
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
